import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import '../../theme/theme_color.dart';
import '../../utils/default/Empty.dart';
import '../../widget/icon_text.dart';
import '../user/profile.dart';

//红娘首页
class MatcherDetailUi extends StatelessWidget {
  final String matcherId;
  final int realSex;

  const MatcherDetailUi(this.matcherId, this.realSex, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _MatcherDetailWidget(matcherId, realSex);
  }
}

class _MatcherDetailWidget extends StatefulWidget {
  final String matcherId;
  final int realSex;

  const _MatcherDetailWidget(this.matcherId, this.realSex, {Key? key})
      : super(key: key);

  @override
  State<_MatcherDetailWidget> createState() => _MatcherDetailWidgetState();
}

class _MatcherDetailWidgetState extends State<_MatcherDetailWidget>
    with TickerProviderStateMixin {
  late double _screenWidth;

  // final _titles = ["男粉丝", "女粉丝"];
  final _titles = [
    '粉丝团',
  ];
  late TabController _tabController;
  late PageController _pageController;
  Map _userInfo = {};

  void _onTabChanged(int index) {
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  void _onPageChanged(int index) {
    _tabController.animateTo(index,
        duration: const Duration(milliseconds: 300));
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _titles.length, vsync: this);
    _pageController = PageController();
    _getMemberInfo();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    _screenWidth = screenSize.width;
    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      childWidget: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [_buildBanner(), _buildUserInfo()];
          },
          body: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //  AppWidget.statusBar(),
              SizedBox(
                width: 100,
                child: _buildTabBar(),
              ),
              Expanded(child: _buildViewPager())
            ],
          )),
    );
  }

  /// viewpager
  Widget _buildViewPager() {
    return PageView.builder(
      controller: _pageController,
      physics: const BouncingScrollPhysics(),
      itemCount: _titles.length,
      onPageChanged: _onPageChanged,
      itemBuilder: (context, index) {
        return _MatcherFans(
          type: index,
          memberId: widget.matcherId,
          realSex: widget.realSex,
        );
      },
    );
  }

  /// 轮播图
  Widget _buildBanner() {
    List<String> imgList = _userInfo?["memberAvatarList"] ?? [];

    final avatar = _userInfo?["profilePhoto"];
    if (imgList.isEmpty && avatar != null && avatar.toString().isNotEmpty) {
      for (var item in _userInfo?["photos"]) {
        imgList.add(item['profilePhoto']);
      }
    }

    double indicatorWidth =
        (_screenWidth - 24 - (imgList.length - 1) * 2.5) / imgList.length;
    return SliverToBoxAdapter(
      child: AspectRatio(
        //设置图片的展示比例之后，可以不设置外层的宽度，或者设置成infinity
        aspectRatio: 1 / 1,
        child: Swiper(
          itemCount: imgList.length,
          itemBuilder: (BuildContext context, int index) {
            return Stack(
              children: [
                Center(
                  child: Container(
                      height: 450,
                      padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                      color: Colors.white,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(7),
                        child: Image.network(
                          imgList[index],
                          fit: BoxFit.fill,
                        ),
                      )),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(top: 250, right: 30),
                      child: _userInfo['singleState'] == 1
                          ? Image.asset(
                              "images/ic_fdsbzh.png",
                              width: 126,
                              height: 96,
                              fit: BoxFit.fill,
                            )
                          : Container(),
                    ),
                  ],
                )
              ],
            );
          },
          //分页指示器
          pagination: SwiperPagination(
              alignment: Alignment.topCenter,
              builder: RectSwiperPaginationBuilder(
                  color: const Color(0x76FFFFFF),
                  activeColor: Colors.white,
                  size: Size(indicatorWidth, 4),
                  activeSize: Size(indicatorWidth, 4),
                  space: 2.5)),
          //页面上的左右箭头
          control: null,
          //自动轮播
          autoplay: false,
          loop: false,
        ),
      ),
    );
  }

  /// 用户简介
  Widget _buildUserInfo() {
    return SliverToBoxAdapter(
        child: InkWell(
            onTap: () {
              if (_userInfo['id'].toString().isNotEmpty) {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (ctx) =>
                        UserProfileUi(memberId: _userInfo['id'].toString())));
              }
            },
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(
                      top: 12, left: 12, right: 12, bottom: 8),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1, color: ThemeColor.dividerColor))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Text(
                                _userInfo['nickName'] ?? "",
                                style: TextStyle(
                                    fontSize: 16, color: ThemeColor.textColor),
                              ),
                              const SizedBox(
                                width: 5,
                              ),
                              // Image.asset('images/ic_vipimg.png',width: 16,height: 16,),
                            ],
                          ),
                          Row(
                            children: [
                              Container(
                                width: 60,
                                height: 20,
                                alignment: Alignment.center,
                                decoration: ShapeDecoration(
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5),
                                  ),
                                  color: _userInfo['isRealAuth'] == 1
                                      ? const Color.fromRGBO(
                                          127, 105, 217, 0.14)
                                      : const Color.fromRGBO(
                                          170, 170, 170, 0.14),
                                ),
                                child: Text.rich(
                                  TextSpan(
                                    style: TextStyle(
                                        fontSize: 10,
                                        color: _userInfo['isRealAuth'] == 1
                                            ? const Color(0xFF7F69D9)
                                            : const Color.fromRGBO(
                                                170, 170, 170, 1)),
                                    children: [
                                      WidgetSpan(
                                        child: Image.asset(
                                            _userInfo['isRealAuth'] == 1
                                                ? 'images/ic_myStatusSec.png'
                                                : 'images/ic_myNoStatusSec.png',
                                            width: 10,
                                            height: 10),
                                      ),
                                      TextSpan(
                                        text: _userInfo['isRealAuth'] == 1
                                            ? ' 已实名'
                                            : ' 未实名',
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      const SizedBox(
                        height: 5,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                alignment: Alignment.center,
                                decoration: ShapeDecoration(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    color: _userInfo['realSex'] == 2
                                        ? ThemeColor.mainColor
                                        : Colors.blue),
                                width: 40,
                                height: 16,
                                child: IconText(
                                  _userInfo['age'].toString() ?? '',
                                  icon: Icon(
                                      _userInfo['realSex'] == 2
                                          ? Icons.female
                                          : Icons.male,
                                      color: Colors.white),
                                  iconSize: 12,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(left: 5),
                                child: Image.asset(
                                  "images/ic_path.png",
                                  width: 11,
                                  height: 13,
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.only(left: 3),
                                child: Text(
                                  '${_userInfo['homeAddr'] ?? ''}',
                                  // '北京 市朝阳区/女♀/24岁',
                                  style: const TextStyle(
                                      fontSize: 12, color: Colors.grey),
                                ),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              Image.asset(
                                'images/ic_houseimg.png',
                                width: 16,
                                height: 16,
                              ),
                              const SizedBox(
                                width: 5,
                              ),
                              Image.asset(
                                'images/ic_carimg.png',
                                width: 16,
                                height: 16,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            )));
  }

  /// 标签选项
  Widget _buildTabBar() {
    return TabBar(
      controller: _tabController,
      tabs: _titles.map((e) => Tab(text: e)).toList(),
      labelColor: ThemeColor.appColor,
      labelStyle: TextStyle(
          color: ThemeColor.textColor,
          fontWeight: FontWeight.bold,
          fontSize: 16),
      unselectedLabelColor: ThemeColor.textColorSecond,
      unselectedLabelStyle:
          TextStyle(color: ThemeColor.textColorSecond, fontSize: 14),
      isScrollable: false,
      indicatorColor: ThemeColor.appColor,
      indicatorSize: TabBarIndicatorSize.label,
      indicatorPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
      onTap: _onTabChanged,
    );
  }

  _getMemberInfo() async {
    final res = await Api.getInstance().getFriendInfo(widget.matcherId);
    if (res['code'] == 0) {
      final data = res['data'];
      setState(() {
        _userInfo = data;
      });
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}

class _MatcherFans extends StatefulWidget {
  final int type;
  final String memberId;
  final int realSex;

  const _MatcherFans(
      {Key? key,
      required this.type,
      required this.memberId,
      required this.realSex})
      : super(key: key);

  @override
  State<_MatcherFans> createState() => _MatcherFansState();
}

class _MatcherFansState extends State<_MatcherFans> {
  int _pageNo = 1;
  final List _list = [];
  bool isShowEmpty = false; //是否显示缺省页面

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('cccc ${widget.realSex}');
    _getList(widget.realSex);
  }

  @override
  Widget build(BuildContext context) {
    return isShowEmpty
        ? const Empty()
        : ListView.builder(
            itemCount: _list.length,
            itemBuilder: (ctx, index) {
              final itemData = _list[index];
              return GestureDetector(
                  onTap: () {
                    if (itemData['id'].toString().isNotEmpty) {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (ctx) =>
                              UserProfileUi(memberId: itemData['id'])));
                    }
                  },
                  child: Column(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    width: 1, color: ThemeColor.dividerColor))),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Stack(
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.only(
                                                left: 5, top: 5),
                                            child: ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(11),
                                              child: AppWidget.blurFixImage(
                                                  imgWidth: 50,
                                                  url: itemData['avatarImg'],
                                                  sign: 0,
                                                  sigmaNum: 1.5),
                                            ),
                                          ),

                                          itemData['singleState'] == 1
                                              ? Container(
                                                  padding:
                                                      const EdgeInsets.only(
                                                          top: 3, left: 1),
                                                  child: Image.asset(
                                                    "images/ic_fdsbzh_out.png",
                                                    width: 64,
                                                    // height: 100,
                                                  ),
                                                )
                                              : Container(),
                                          // itemData['singleState'] == 1 ?Container(
                                          //   // alignment: Alignment.bottomRight,
                                          //     margin: const EdgeInsets.only(top: 0, left: 2),
                                          //     child: Stack(
                                          //       children: [
                                          //
                                          //         Image.asset(
                                          //           "images/ic_imgTop.png",
                                          //           width: 49,
                                          //         ),
                                          //         const Positioned(
                                          //           right: 3,
                                          //           child: Text('非单身',style: TextStyle(
                                          //             color: Colors.white,
                                          //             fontSize: 9,
                                          //           )),
                                          //         )
                                          //
                                          //       ],
                                          //     )
                                          // ):Container(),
                                          // itemData['singleState'] == 1 ? Container(
                                          //   // alignment: Alignment.bottomLeft,
                                          //     margin: const EdgeInsets.only(top: 36, right: 2),
                                          //     child:Stack(
                                          //       children: [
                                          //         Image.asset(
                                          //           "images/ic_imgBottom.png",
                                          //           width: 49,
                                          //           // height: 14,
                                          //         ),
                                          //         const Positioned(
                                          //           left: 3,
                                          //           child: Text('不征婚',style: TextStyle(
                                          //             color: Colors.white,
                                          //             fontSize: 9,
                                          //           )),
                                          //         )
                                          //
                                          //       ],
                                          //     )
                                          // ):Container(),
                                        ],
                                      ),
                                      // const SizedBox( width: 5,),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const SizedBox(
                                            height: 6,
                                          ),
                                          Row(
                                            children: [
                                              const SizedBox(
                                                width: 8,
                                              ),
                                              SizedBox(
                                                width: 200,
                                                child: Text(
                                                  itemData['nickName'] ?? "",
                                                  style: TextStyle(
                                                      fontSize: 16,
                                                      color:
                                                          ThemeColor.textColor,
                                                      overflow: TextOverflow
                                                          .ellipsis),
                                                ),
                                              )
                                            ],
                                          ),
                                          const SizedBox(
                                            height: 5,
                                          ),
                                          Row(
                                            children: [
                                              const SizedBox(
                                                width: 8,
                                              ),
                                              Container(
                                                alignment: Alignment.center,
                                                decoration: ShapeDecoration(
                                                    shape:
                                                        RoundedRectangleBorder(
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              8),
                                                    ),
                                                    color:
                                                        itemData['realSex'] == 2
                                                            ? ThemeColor
                                                                .mainColor
                                                            : Colors.blue),
                                                width: 40,
                                                height: 16,
                                                child: IconText(
                                                  itemData['age'].toString(),
                                                  icon: Icon(
                                                      itemData['realSex'] == 2
                                                          ? Icons.female
                                                          : Icons.male,
                                                      color: Colors.white),
                                                  iconSize: 12,
                                                  style: const TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 12,
                                                  ),
                                                ),
                                              ),
                                              const SizedBox(
                                                width: 5,
                                              ),
                                              Image.asset(
                                                "images/ic_path.png",
                                                width: 11,
                                                height: 13,
                                              ),
                                              const SizedBox(
                                                width: 3,
                                              ),
                                              Text(
                                                '${itemData['homeAddr'] ?? ''}',
                                                // '北京 市朝阳区/女♀/24岁',
                                                style: const TextStyle(
                                                    fontSize: 12,
                                                    color: Colors.grey),
                                              ),
                                            ],
                                          )
                                        ],
                                      )
                                    ]),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  // mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    Container(
                                      width: 60,
                                      height: 20,
                                      alignment: Alignment.center,
                                      // margin: const EdgeInsets.symmetric(horizontal: 14),
                                      // margin: const EdgeInsets.symmetric(horizontal: 20,vertical: 5),
                                      decoration: ShapeDecoration(
                                        shape: RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(5),
                                        ),
                                        color: itemData['isRealAuth'] == 1
                                            ? const Color.fromRGBO(
                                                127, 105, 217, 0.14)
                                            : const Color.fromRGBO(
                                                170, 170, 170, 0.14),
                                      ),
                                      child: Text.rich(
                                        TextSpan(
                                          style: TextStyle(
                                              fontSize: 10,
                                              color: itemData['isRealAuth'] == 1
                                                  ? const Color(0xFF7F69D9)
                                                  : const Color.fromRGBO(
                                                      170, 170, 170, 1)),
                                          children: [
                                            WidgetSpan(
                                              child: Image.asset(
                                                  itemData['isRealAuth'] == 1
                                                      ? 'images/ic_myStatusSec.png'
                                                      : 'images/ic_myNoStatusSec.png',
                                                  width: 10,
                                                  height: 10),
                                            ),
                                            TextSpan(
                                              text: itemData['isRealAuth'] == 1
                                                  ? ' 已实名'
                                                  : ' 未实名',
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 16,
                                    ),
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [],
                                        ),
                                        Row(
                                          children: [
                                            Image.asset(
                                              'images/ic_houseimg.png',
                                              width: 16,
                                              height: 16,
                                            ),
                                            const SizedBox(
                                              width: 5,
                                            ),
                                            Image.asset(
                                              'images/ic_carimg.png',
                                              width: 16,
                                              height: 16,
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ));
            },
          );
  }

  _getList(int realSex) async {
    final res = await Api.getInstance().getMatcherFans(
      widget.memberId,
      _pageNo++,
      20,
      realSex,
    );
    if (res != null && res['code'] == 0) {
      List list = res['data']['list'];
      if (_pageNo <= 1) {
        _list.clear();
      }
      if (list.isNotEmpty == true) {
        setState(() {
          isShowEmpty = false;
          _list.addAll(list);
        });
      } else {
        setState(() {
          isShowEmpty = true;
        });
      }
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }
}
